﻿#pragma once

#include "RBTreeForWrap.h"

namespace my_map
{
	template<class K, class V>
	class map
	{
		struct MapKeyOfT
		{
			const K& operator()(const pair<const K,V>& kv)
			{
				return kv.first;
			}
		};
	private:   
		RBTreeForWrap<K, pair<const K, V>, MapKeyOfT> _t;
	public:
		typedef typename RBTreeForWrap<K,  pair<const K, V>, MapKeyOfT>::iterator iterator;//套一层而已

		iterator begin()
		{
			return _t.begin();
		}

		iterator end()
		{
			return _t.end();
		}

		//[]配合插入，如果没有key这个值，就插入；没有就返回key对应value的引用
		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = _t.Insert(make_pair(key, V()));
			return ret.first->second;
		}

		pair<iterator,bool> insert(const pair<const K, V>& kv)
		{
			return _t.Insert(kv);
		}

	};

	void test_map1()
	{
		map<int,int> m;
		m.insert(make_pair(1,1));
		m.insert(make_pair(3,3));
		m.insert(make_pair(2,2));
	}

	void test_map2()
	{
		map<string, string> dict;
		dict.insert(make_pair("sort", "排序"));
		dict.insert(make_pair("string","字符串"));
		dict.insert(make_pair("count", "计数"));
		dict.insert(make_pair("string", "(字符串)"));

		map<string, string>::iterator it = dict.begin();
		while (it != dict.end())
		{
			cout << it->first << ":" << it->second << endl;
			/*it->first = "1111";//不能修改,因为pair中的K使用const修饰了
			it->second = "111";*///可以修改

			++it;
		}
		cout << endl;

		for (auto& kv : dict)
		{
			cout << kv.first << ":" << kv.second << endl;
		}
		cout << endl;
	}

	void test_map3()
	{
		string arr[] = {"西瓜","西瓜","苹果","西瓜","苹果","苹果","香蕉","梨"};
		map<string, int> countMap;
		for (auto& e : arr)
		{
			countMap[e]++;
		}

		for (auto& kv : countMap)
		{
			cout << kv.first << ":" << kv.second << endl;
		}
	}
}